package wei.qiang.ye.sbspringmvcdemo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import wei.qiang.ye.sbspringmvcdemo.common.ServiceException;
import wei.qiang.ye.sbspringmvcdemo.entity.User;
import wei.qiang.ye.sbspringmvcdemo.enums.ResponseEnum;
import wei.qiang.ye.sbspringmvcdemo.enums.ServiceExceptionEnum;

import java.util.*;

@RestController
@RequestMapping("/users")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(getClass());


    private static List<User> userList = new ArrayList<>();
    private static Map<String,String> uidMap = new HashMap<>();
    /**
     * 这里使用静态数据，模拟数据库的数据
     */
    static {
        User user1 = new User();
        user1.setUid("1");
        user1.setUsername("aa");
        User user2 = new User();
        user2.setUid("2");
        user2.setUsername("bb");
        User user3 = new User();
        user3.setUid("3");
        user3.setUsername("cc");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        uidMap.put(user1.getUid(), user1.getUsername());
        uidMap.put(user2.getUid(), user2.getUsername());
        uidMap.put(user3.getUid(), user3.getUsername());
    }

    /**
     * 查询用户列表
     *
     * @return 用户列表
     */
    @GetMapping("")
    public List<User> list() {
        return userList;
    }

    /**
     * 获得指定用户编号的用户
     *
     * @param uid 用户编号
     * @return 用户
     */
    @GetMapping("/{uid}")
    public User get(@PathVariable("uid") String uid) {
        // 查询并返回用户
        for (User u : userList) {
            if (uid.equals(u.getUid())) {
                return u;
            }
        }
        //返回空对象
        return new User();
    }

    @GetMapping("/search-one/{uid}")
    public User getPlus(@PathVariable("uid") String uid) {
        // 查询并返回用户
        for (User u : userList) {
            if (uid.equals(u.getUid())) {
                return u;
            }
        }
        //返回空对象
        return new User();
    }

    /**
     * 添加用户
     *
     * @return 添加成功的用户编号
     */
    @PostMapping("/add")
    public User add(User user) throws Exception {
        userList.add(user);
        return user;
    }

    /**
     * 更新指定用户编号的用户
     * @return 是否修改成功
     */
    @PutMapping("/update")
    public String update(User user) {
        //用户不存在，则保存新用户，否则更新该用户
        if (!uidMap.containsKey(user.getUid())) {
            //保存用户的更改
            insert(user);
            return ResponseEnum.SUCCESS.getCode();
        }

        //删除旧信息
        remove(user.getUid());
        //保存用户的更改
        insert(user);
        return ResponseEnum.SUCCESS.getCode();
    }

    /**
     * 删除指定用户编号的用户
     *
     * @param uid 用户编号
     * @return 是否删除成功
     */
    @DeleteMapping("/{uid}")
    public String delete(@PathVariable("uid") String uid) {
        remove(uid);
        return ResponseEnum.SUCCESS.getCode();
    }


    /**
     * 测试抛出 NullPointerException 异常
     */
    @GetMapping("/exception-01")
    public User exception01() {
        throw new NullPointerException("空指针异常");
    }

    /**
     * 测试抛出 ServiceException 异常
     */
    @GetMapping("/exception-02")
    public User exception02() {
        throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND);
    }

    @GetMapping("/do-something")
    public void doSomething() {
        logger.info("[doSomething]");
    }

    @GetMapping("/current_user")
    public User currentUser() {
        logger.info("[currentUser]");
        return new User("6","niuniu");
    }

    @GetMapping("/exception-03")
    public void exception03() {
        logger.info("[exception03]");
        throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND);
    }

    @PostMapping(value = "/save",
            //"application/xml"、"application/json" ，针对 Content-Type 请求头
            consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
            //"application/xml"、"application/json" ，针对 Accept 请求头
            produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
    )
    public User save(@RequestBody User user) {
        return user;
    }


    private void remove(String uid) {
        Iterator<User> userIterator = userList.iterator();
        while (userIterator.hasNext()) {
            User user = userIterator.next();
            if (uid.equals(user.getUid())) {
                userIterator.remove();
            }
        }
    }

    private User insert(User user) {
        userList.add(user);
        uidMap.put(user.getUid(),user.getUsername());
        return user;
    }

}
